package com.t365.qmm.mapper;

import com.t365.qmm.pojo.Cart;
import com.t365.qmm.pojo.Goods;
import com.t365.qmm.utils.MyabtisUtil;
import com.t365.qmm.utils.RedisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

class CartMapperTest {

    @Test
    void deleteByPrimaryKey() {
    }

    @Test
    void insert() {
        //新增
        SqlSession session= null;
        try {
            session = MyabtisUtil.createSqlSession_tran(false);

            Cart cart=new Cart();
            Integer userId= 49;
            Integer goodsId =760;
            Integer quantity=2;
            double price=1100;

            cart.setUserid(userId);
            cart.setGoodsId(goodsId);
            cart.setGoodsName("婴儿车");
            cart.setQuantity(quantity);
            cart.setPrice(price);
            cart.setCreatedby(userId);
            session.getMapper(CartMapper.class).insert(cart);

            session.commit();
        } catch (Exception e) {
            session.rollback();
        } finally {
            MyabtisUtil.closeSqlSession(session);
        }
    }

    @Test
    void insertSelective() {
    }

    @Test
    void selectByPrimaryKey() {
    }

    @Test
    void updateByPrimaryKeySelective() {
    }

    @Test
    void updateByPrimaryKey() {
        //改数量
        SqlSession session= MyabtisUtil.createSqlSession_tran(false);

        Cart cart=new Cart();

        Integer userId= 49;
        Integer goodsId =760;
        Integer quantity=1;//从jsp中点击按钮传递过来的数量
        double price=1100;

        cart.setUserid(userId);
       // cart.setGoodsId(goodsId);
        //cart.setGoodsName("婴儿车");
        cart.setQuantity(quantity);//数量
       // cart.setPrice(price);
       // cart.setCreatedby(userId);
        session.getMapper(CartMapper.class).updateByPrimaryKey(cart);

        session.commit();
        MyabtisUtil.closeSqlSession(session);
    }

    @Test
    void getCartsByCondition() {
        SqlSession session= MyabtisUtil.createSqlSession();
        Map<String,Object> maps = new HashMap<String,Object>();

        Integer userId= 49;
        Integer goodsId =760;
        Integer quantity=365;

        maps.put("userId",userId);
        //判断商品xxx是否在该用户的购物车中
        maps.put("goodsId",goodsId);
        List<Cart> cartList = session.getMapper(CartMapper.class).getCartsByCondition(maps);

        //购物车有该商品
        if (null!=cartList){
            //改数量
            Cart cart = cartList.get(0);   //商品
            cart.setQuantity(cart.getQuantity()+quantity);//改数量
            int i = session.getMapper(CartMapper.class).updateByPrimaryKey(cart);

        }else{
            //新增至购物车
        }
        //扣减库存

        System.out.println("商品已成功添加至购物车");
        MyabtisUtil.closeSqlSession(session);
    }
}